//遍历路由文件拿到路由

import { IBreadcurmb } from '@/base-ui/breadcurmb'
import { RouteRecordRaw } from 'vue-router'

let firstMenu: any = null

export function mapMenusToRoutes(userMenus: any): RouteRecordRaw[]{
  const routes: RouteRecordRaw[] = []
  //1.先去加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = []
  //递归查找文件夹
  const routeFiles = require.context('../router/main',true,/\.ts/)
  routeFiles.keys().forEach((key) => {
    // console.log(key)
    //./system/user.user.ts  根据 . 切割拿到路径
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })
  // console.log(allRoutes)
  //2.根据菜单获取需要的routes
  const _recurseGetRoute = (menus: any[]) => {
    for(const menu of menus){
      if(menu.type ==  2){
        const route = allRoutes.find((route) => {
          return route.path === menu.url
        })
        if(route) routes.push(route)
        if(!firstMenu){
          firstMenu = menu
        }
      }else{
        _recurseGetRoute(menu.children)
      }
    }
  }

  _recurseGetRoute(userMenus)
  return routes
}

export function pathMaptoMenu(userMenus: any[],currentPath: string,breadcurmbs?: IBreadcurmb[]): any{
  for(const menu of userMenus){
    if(menu.type === 1){
      const findMenu = pathMaptoMenu(menu.children ?? [],currentPath)
      if(findMenu){
        breadcurmbs?.push({name:menu.name})
        breadcurmbs?.push({name:findMenu.name})
        return findMenu
      }
    }else if(menu.type === 2 && menu.url === currentPath){
      return menu
    }
  }
}

export { firstMenu }

export function pathMapBreadcurmbs(userMenus: any[],currentPath: string){
  const breadcurmbs: IBreadcurmb[] = []
  pathMaptoMenu(userMenus,currentPath,breadcurmbs)
  return breadcurmbs
}

export function mapMenusToPermissions(userMenus: any[]){
  const permissions: string[] = []
  const _recurseGetPermission = (menus: any[]) => {
    for(const menu of menus){
      if(menu.type == 1 || menu.type == 2){
        _recurseGetPermission(menu.children ?? [])
      }else if(menu.type == 3){
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermission(userMenus)
  return permissions
}
//获取菜单里面的叶子节点
export function mapMenusLeafKeys(menuList: any[]){
  const leftKeys: number[] = []
  const _recurseGetLraf = (menuList: any[]) => {
    for(const menu of menuList){
      if(menu.children){
        _recurseGetLraf(menu.children)
      }else{
        leftKeys.push(menu.id)
      }
    }
  }
  _recurseGetLraf(menuList)
  return leftKeys
}
